﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Data;
using System.Drawing;
//using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Commons.CommonHelper;

namespace BuildingForm
{
    public partial class BlackPersonsForm : Form, IModuleExtension 
    {
        private string title = "添加";
        private int nid = 0;
        public BlackPersonsForm()
        {
            InitializeComponent();
            Init();
            bind();
        }
        private MyOpaqueLayer.MyOpaqueLayer m_OpaqueLayer = null;
        private void Init()
        {
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.ShowIcon = false;
            //表头加粗，居中
            foreach (DataGridViewColumn col in this.dataGridView1.Columns)
            {
                col.SortMode = DataGridViewColumnSortMode.NotSortable;
            }
            this.dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            this.dataGridView1.ColumnHeadersDefaultCellStyle.Font  = new System.Drawing.Font("SimSun", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.txtName.Text = "";
            this.txtCode.Text = "";
            this.txtRemark.Text = "";
            List<string> list = new List<string>();
            list.Add("全部");
            list.Add("男");
            list.Add("女");
            List<string> list2 = new List<string>();
            list2.Add("男");
            list2.Add("女");
            this.cobSex.DataSource = list;
            this.cobSex_p1.DataSource = list2;
            this.panel1.BorderStyle = BorderStyle.FixedSingle;
            panel1.Location = new Point((this.Size.Width - panel1.Size.Width) / 2, (this.Size.Height - panel1.Size.Height) / 2);
            dataGridView1.AllowUserToAddRows = false;
            hide();
        }
        public void bind()
        {
            string name = txtName.Text.ToString().Trim();
            string code = txtCode.Text.ToString().Trim();
            string remark = txtRemark.Text.ToString().Trim();
            string sex = cobSex.Text.ToString().Trim();
            string sql = "1=1";
            if (!string.IsNullOrEmpty(name))
            {
                sql += " and Name like '%" + name + "%'";
            }
            if (!string.IsNullOrEmpty(code))
            {
                sql += " and SFZH like '%" + code + "%'";
            }
            if (!string.IsNullOrEmpty(remark))
            {
                sql += " and Remark like '%" + remark + "%'";
            }
            if (sex != "全部")
            {
                int ssex = sex == "男" ? 1 : 0;
                sql += " and sex =" + ssex;
            }
            sql += " order by createtime desc";
            Maticsoft.DAL.BlackPersons per = new Maticsoft.DAL.BlackPersons();
            DataSet ds=per.GetList (sql);
            DataTable dt = ds.Tables[0];
            this.dataGridView1.AutoGenerateColumns = false;
            this.dataGridView1.DataSource = dt;
            
        }
        private void show()
        {
            if (this.m_OpaqueLayer == null)
            {
                this.m_OpaqueLayer = new MyOpaqueLayer.MyOpaqueLayer(125, false);
                this.Controls.Add(this.m_OpaqueLayer);
                this.m_OpaqueLayer.Dock = DockStyle.Fill;
                this.m_OpaqueLayer.BringToFront();
            }
            this.m_OpaqueLayer.Enabled = true;
            this.m_OpaqueLayer.Visible = true;

            //panel1在悬浮层上显示

            panel1.BackColor = Color.White;

            m_OpaqueLayer.Controls.Add(panel1);
            panel1.Show();
        }
        private void hide()
        {
            panel1.Hide();
            if (this.m_OpaqueLayer != null)
            {
                this.m_OpaqueLayer.Visible = false;
                this.m_OpaqueLayer.Enabled = false;
            }
        }
        private DataTable bind2()
        {
            string name = txtName.Text.ToString().Trim();
            string code = txtCode.Text.ToString().Trim();
            string remark = txtRemark.Text.ToString().Trim();
            string sex = cobSex.Text.ToString().Trim();
            string sql = "1=1";
            if (!string.IsNullOrEmpty(name))
            {
                sql += " and Name like '%" + name + "%'";
            }
            if (!string.IsNullOrEmpty(code))
            {
                sql += " and SFZH like '%" + code + "%'";
            }
            if (!string.IsNullOrEmpty(remark))
            {
                sql += " and Remark like '%" + remark + "%'";
            }
            if (sex != "全部")
            {
                int ssex = sex == "男" ? 1 : 0;
                sql += " and sex =" + ssex;
            }
            sql += " order by createtime desc";
            Maticsoft.DAL.BlackPersons per = new Maticsoft.DAL.BlackPersons();
            DataSet ds = per.GetList2(sql);
            DataTable dt = ds.Tables[0];
            return dt;
        }
       
        private void btnLead_Click(object sender, EventArgs e)
        {
            openFile.Title = "选择文件";
            openFile.Filter = " xls files(*.xls)|*.xls";
            openFile.FilterIndex = 1;
            openFile.RestoreDirectory = true;
            if (openFile.ShowDialog().Equals(DialogResult.OK))
            {
                DataTable dt = ExcelHelper.RenderDataTableFromExcel(openFile.FileName, 0, 0);
                if (dt.Columns.Count != 6)
                {
                    MessageBox.Show("文件格式不对！"); return;
                }
                try
                {
                    //筛选已存在黑名单
                    Maticsoft.DAL.BlackPersons per = new Maticsoft.DAL.BlackPersons();
                    List<string> strList = new List<string>();
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        strList.Add(dt.Rows[i]["身份证"].ToString().Trim());
                    }
                    string str = String.Join("','", strList.ToArray());
                    string sql = " SFZH in ( '" + str + "' )";
                    DataTable dt2 = per.GetList(sql).Tables[0];
                    List<string> strList2 = new List<string>();
                    for (int i = 0; i < dt2.Rows.Count; i++)
                    {
                        strList2.Add(dt2.Rows[i]["nsfzh"].ToString().Trim());
                    }
                    bool isT = true;
                    for (int i=0;i<dt.Rows .Count;i++)
                    {
                        DataRow dr = dt.Rows[i];
                        Maticsoft.Model.BlackPersons model = new Maticsoft.Model.BlackPersons();
                        string code = dr.ItemArray[2].ToString().Trim();
                        if (strList2.Contains(code))
                        {
                            continue;
                        }
                        string name = dr.ItemArray[1].ToString().Trim();
                        string sex = dr.ItemArray[3].ToString().Trim();
                        string remark = dr.ItemArray[4].ToString().Trim();
                        //"1/26/15"
                        string time = dr.ItemArray[5].ToString().Trim();
                        if (time.IndexOf('/')>=0)
                        {
                            string[] ar = time.Split('/');
                            time = ar[0] + "/" + ar[1] + "/" + "20" + ar[2];
                        }
                        int num=i+2;
                        if (string.IsNullOrEmpty(name))
                        {
                            MessageBox.Show("第" + num + "行姓名为空！"); return;
                        }
                        if (string.IsNullOrEmpty(code))
                        {
                            MessageBox.Show("第" + num + "行身份证为空！"); return;
                        }
                        if (string.IsNullOrEmpty(sex))
                        {
                            MessageBox.Show("第" + num + "行性别为空！"); return;
                        }
                        if (string.IsNullOrEmpty(remark))
                        {
                            MessageBox.Show("第" + num + "行问题原因为空！"); return;
                        }
                        if (string.IsNullOrEmpty(time))
                        {
                            MessageBox.Show("第" + num + "行登记时间为空！"); return;
                        }
                        DateTime createtime = Convert.ToDateTime(time);
                        model.Name = name;
                        model.Remark = remark;
                        model.sex = sex == "男" ? true : false;
                        model.SFZH = code;
                        model.createtime = createtime;
                        isT=per.Add(model)>0;
                        if (!isT)
                        {
                            MessageBox.Show("导入文件故障！"); return;
                        }
                    }
                    if (isT)
                    {
                        bind();
                        MessageBox.Show("导入数据成功！"); return;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("文件格式不对！"); return;
                }    
            }
        }

        private void BlackPersons_Load(object sender, EventArgs e)
        {

        }

        private void btnCheck_Click(object sender, EventArgs e)
        {
            Maticsoft.DAL.BlackPersons per = new Maticsoft.DAL.BlackPersons();
            Maticsoft.DAL.Ry_Info info=new Maticsoft.DAL.Ry_Info ();
            DataTable dt = per.GetList("").Tables[0];
            List<string> strList = new List<string>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                strList.Add(dt.Rows[i]["nsfzh"].ToString().Trim());
            }
            string str = String.Join("','", strList.ToArray ());
            string sql = " sfzh in ( '" + str + "' )";
            DataTable dt2 = info.GetList(sql).Tables[0];
            if (dt2.Rows.Count == 0)
            {
                MessageBox.Show("在现有人员库中没有检测到黑名单！");
            }
            else
            {
                DelExistPerson form = new DelExistPerson();
                form.Show();
            }
        }

        private void btnExistAdd_Click(object sender, EventArgs e)
        {
            AllPersons p = new AllPersons(this);
            p.Show();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            this.title = "添加";
            this.lblTitle.Text = "添加黑名单";
            this.btnAdd_p1.Text = "添加";
            this.txtName_p1.Text = "";
            this.txtCode_p1.Enabled = true;
            this.txtCode_p1.Text = "";
            this.txtRemark_p1.Text = "";
            this.cobSex_p1.Text = "男";
            show();
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            bind();
        }
        private void btnAdd_p1_Click(object sender, EventArgs e)
        {
            string name = this.txtName_p1.Text.ToString().Trim();
            string sex = this.cobSex_p1.Text.ToString().Trim();
            string code = this.txtCode_p1.Text.ToString().Trim();
            string remark = this.txtRemark_p1.Text.ToString().Trim();
            if (string.IsNullOrEmpty(name))
            {
                MessageBox.Show("请输入姓名！"); return;
            }
            if (name.Length > 10)
            {
                MessageBox.Show("姓名太长了！"); return;
            }
            if (string.IsNullOrEmpty(code))
            {
                MessageBox.Show("请输入身份证号！"); return;
            }
            if (code.Length > 18)
            {
                MessageBox.Show("身份证号超出范围！"); return;
            }
            if (string.IsNullOrEmpty(remark))
            {
                MessageBox.Show("请输入问题原因！"); return;
            }
            if (remark.Length > 50)
            {
                MessageBox.Show("问题原因太长！"); return;
            }
            Maticsoft.Model.BlackPersons per = new Maticsoft.Model.BlackPersons();
            Maticsoft.DAL.BlackPersons dao = new Maticsoft.DAL.BlackPersons();
            per.ID = nid;
            per.Name = name;
            per.sex = sex == "男" ? true : false;
            per.SFZH = code;
            per.Remark = remark;
            per.createtime = DateTime.Now;
            if (title == "添加")
            {
                string sql = " SFZH='" + code + "'";
                DataTable dt = dao.GetList(sql).Tables[0];
                if (dt.Rows.Count > 0)
                {
                    MessageBox.Show("该人员已存在！"); return;
                }

                bool isT = dao.Add(per) > 0;
                hide();
                if (isT)
                {
                    MessageBox.Show(title + "黑名单成功！");
                }
                else
                {
                    MessageBox.Show(title + "黑名单失败！");
                }
            }
            else
            {
                bool isT = dao.Update(per);
                if (isT)
                {
                    MessageBox.Show(title + "黑名单成功！");
                }
                else
                {
                    MessageBox.Show(title + "黑名单失败！");
                }
            }
            bind();
            hide();
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            try
            {
                SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                //设置文件类型   
                saveFileDialog1.Filter = " xls files(*.xls)|*.xls";
                //设置默认文件类型显示顺序   
                saveFileDialog1.FilterIndex = 2;
                //保存对话框是否记忆上次打开的目录   
                saveFileDialog1.RestoreDirectory = true;
                saveFileDialog1.FileName = "黑名单记录表格";
                //点了保存按钮进入   
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    string fileName = saveFileDialog1.FileName;

                    DataTable dt = bind2();
                    string[] cols = new string[] { "序号", "姓名", "身份证", "性别", "问题原因", "登记时间" };
                    ExcelHelper.Export(dt, "黑名单记录表格", fileName, "sheet1", cols, cols);
                    //ExcelHelper.Export(dt, "黑名单记录表格", saveFileDialog1.FileName, "sheet1");
                    MessageBox.Show("导出文件成功！"); return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("导出文件故障！"); return;
            }
        }
     
        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1) return;
            if (this.dataGridView1.Columns[e.ColumnIndex].Name == "btnUpdate")
            {
                this.title = "修改";
                this.lblTitle.Text = "修改黑名单";
                this.btnAdd_p1.Text = "修改";
                DataGridViewRow r = dataGridView1.Rows[e.RowIndex];
                string code = r.Cells[3].Value.ToString().Trim();
                string name = r.Cells[1].Value.ToString().Trim();
                string sex = r.Cells[2].Value.ToString().Trim();
                string remark = r.Cells[4].Value.ToString().Trim();
                nid = Convert.ToInt32(r.Cells[8].Value);
                this.txtCode_p1.Text = code;
                this.txtCode_p1.Enabled = false;
                this.txtName_p1.Text = name;
                this.txtRemark_p1.Text = remark;
                this.cobSex_p1.Text = sex;
                show();
            }
            if (this.dataGridView1.Columns[e.ColumnIndex].Name == "btnDel")
            {
                if (MessageBox.Show("您确定要删除吗？", "提示：", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk) == DialogResult.Yes)
                {
                    DataGridViewRow r = dataGridView1.Rows[e.RowIndex];
                    int id = Convert.ToInt32(r.Cells[8].Value);
                    Maticsoft.DAL.BlackPersons per = new Maticsoft.DAL.BlackPersons();
                    bool isT = per.Delete(id);
                    if (isT)
                    {
                        MessageBox.Show("删除成功！");
                    }
                    else
                    {
                        MessageBox.Show("删除失败！");
                    }
                }
            }
            bind();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            hide();
        }

        private void txtCode_p1_KeyPress(object sender, KeyPressEventArgs e)
        {
            //if (!((e.KeyChar >= 48 && e.KeyChar <= 57) || e.KeyChar == 8))
            //{
            //    e.Handled = true;
            //}  
        }

        
        /// <summary>
        /// 调用窗口
        /// </summary>
        /// <param name="title">窗体名称</param>
        /// <param name="xmmc">项目名称</param>
        /// <returns></returns>
        public bool ShowExtension(string title, string xmmc)
        {
            try
            {
                BlackPersonsForm bpf = new BlackPersonsForm();
                //bpf.Text = title;
                //bpf.Tag = xmmc;
                bpf.ShowDialog();
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("加载失败！");
                return false;
            }
        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }
    }
}
